package com.jdy.haoduoai.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.AlbumItem;
import com.jdy.haoduoai.model.CartoonVo;
import com.jdy.haoduoai.model.CategoryItem;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.util.ACache;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.ycsj.goldmedalnewconcept.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import static com.ycsj.goldmedalnewconcept.R.id.province;

//import com.jdy.haoduoai.R;

public class ExpandListActivity extends BaseActivity {

    private CategoryItem categoryItem = null;
    private String title;
    private JSONArray jsonArr;
    private ACache mCache;

    private ArrayList<CartoonVo> mArrayList = null;

    private void loadData() {
        new CustomAsyncTask(this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                //dismissLoading();
                if (result.isSuccess()) {

                    try {
                        JSONObject json = new JSONObject(result.data);
                        String data = json.optString("data");
                        final JSONArray array = new JSONArray(data);

                        new Thread() {
                            @Override
                            public void run() {
                                if (jsonArr != null) {
                                    mCache.remove(title);
                                }
                                mCache.put(title, array);
                            };
                        }.start();


//                        if (isrefreshlist) {
//                            mArrayList.clear();
//                        }
                        mArrayList.clear();

                        for (int i = 0; i < array.length(); i++) {
                            JSONObject obj = ((JSONObject) array.opt(i));

                            if (Tools.isNotEmpty(obj.toString())) {
                                CartoonVo itemVo = JsonSerializer.getInstance()
                                        .deserialize(obj.toString(), CartoonVo.class);
                                mArrayList.add(itemVo);
                            }

                        }
                    } catch (Exception e) {
                    }
                   // mArrayList.addAll(mAdapterList);
                   setView();
                } else {
//                    toastShow(result.data.toString());
//                    pullToRefreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
//                    pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
                if (lu == null) {
                    lu = Tools.restoreLeUser();
                }

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                if (categoryItem != null) {
                    param_.put("category_id", categoryItem.id);
                } /*else if (searchKey != null) {
                    param_.put("name", key);
                } else {
                    param_.put("name", key);
                }*/

                param_.put("page", 1);
                param_.put("page_size", 50);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                return HttpUtils.startRequest(HttpUtils.HOST_API
                                + HttpUtils.GET_CATALOG_ALBUM, param_,
                        HttpUtils.TAG_GET_REQUEST);
            }
        }).execute();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main22);

        mCache = ACache.get(this);
        mArrayList = new ArrayList<>();
        mArrayListAlbum = new ArrayList<>();

        Intent intent = getIntent();
        if (intent.getSerializableExtra("categoryitem") != null) {
            categoryItem = (CategoryItem) intent.getSerializableExtra("categoryitem");
            title = categoryItem.name;

            setTitle(categoryItem.name);
            loadData();
        }
    }

    private ArrayList<AlbumItem> mArrayListAlbum = null;

    private void getEpisode(final int album_id, final int groupPosition) {
        new CustomAsyncTask(this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess()) {
                    try {
                        JSONObject json = new JSONObject(result.data);
                        String data = json.optString("data");
                        JSONArray array = new JSONArray(data);

                         mArrayListAlbum.clear();

                        for (int i = 0; i < array.length(); i++) {
                            JSONObject obj = ((JSONObject) array.opt(i));

                            if (Tools.isNotEmpty(obj.toString())) {
                                AlbumItem itemVo = JsonSerializer.getInstance().deserialize(
                                        obj.toString(), AlbumItem.class);
                                mArrayListAlbum.add(itemVo);
                            }

                        }
                    } catch (Exception e) {
                    }

                  //  setView(isLoadMore);
                   // mAdapter.notifyAll();
                    expandableListView.expandGroup(groupPosition);
                } else {
                    if (Tools.isNotNullStr(result.data)) {
                        Toast.makeText(ExpandListActivity.this, result.data,
                                Toast.LENGTH_SHORT).show();
                    }

//                    storylistPullLayout.refreshFinish(PullToRefreshLayout.FAIL);
//                    storylistPullLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
                if (lu == null) {
                    lu = Tools.restoreLeUser();
                }

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                param_.put("album_id", album_id);

                param_.put("page", 1);
                param_.put("page_size", 50);
                return HttpUtils.startRequest(HttpUtils.HOST_API
                        + HttpUtils.GET_EPISODE_LIST, param_, HttpUtils.TAG_GET_REQUEST);
            }
        }).execute();
    }

     ExpandableListAdapter mAdapter = null;
    ExpandableListView expandableListView;

    private void setView() {
        mAdapter = new BaseExpandableListAdapter() {
            // 设置组视图的显示文字
          //  private String[] province = new String[] { "河南省", "河北省", "山东省", "山西省" };
            // 子视图显示文字
            private String[][] city = new String[][] {
                    { "郑州市", "开封市", "新乡市", "安阳市", "南阳市" },
                    { "石家庄市", "邯郸市", "保定市", "廊坊市" },
                    { "济南市", "青岛市", "日照市", "烟台市", "威海市" },
                    { "太原市", "大同市", "晋城市", "吕梁市", "长治市" } };

            // 自己定义一个获得文字信息的方法
            TextView getTextView() {
                AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, 64);
                TextView textView = new TextView(ExpandListActivity.this);
                textView.setLayoutParams(lp);
                textView.setGravity(Gravity.CENTER_VERTICAL);
                textView.setPadding(36, 0, 0, 0);
                textView.setTextSize(20);
                textView.setTextColor(Color.BLACK);
                return textView;
            }

            // 重写ExpandableListAdapter中的各个方法
            @Override
            public int getGroupCount() {
                return mArrayList.size();
            }

            @Override
            public Object getGroup(int groupPosition) {
                //return province[groupPosition];
                return mArrayList.get(groupPosition).name;
            }

            @Override
            public long getGroupId(int groupPosition) {
                return groupPosition;
            }

            @Override
            public int getChildrenCount(int groupPosition) {
                return mArrayListAlbum.size();/*city[groupPosition].length;*/
            }

            @Override
            public Object getChild(int groupPosition, int childPosition) {
                return mArrayListAlbum.get(groupPosition).album_name;//city[groupPosition][childPosition];
            }

            @Override
            public long getChildId(int groupPosition, int childPosition) {
                return childPosition;
            }

            @Override
            public boolean hasStableIds() {
                return true;
            }

            @Override
            public View getGroupView(int groupPosition, final boolean isExpanded,
                                     View convertView, ViewGroup parent) {
                LinearLayout ll = new LinearLayout(ExpandListActivity.this);

                View v = LayoutInflater.from(ExpandListActivity.this).inflate(
                        R.layout.navigation_item, ll, false);

                ll.setOrientation(LinearLayout.HORIZONTAL);
                // TextView textView = getTextView();
                // textView.setTextColor(Color.BLACK);
                // textView.setText(getGroup(groupPosition).toString());

                TextView tv_cc = (TextView) v.findViewById(R.id.tv_cc);
                tv_cc.setText(getGroup(groupPosition).toString());





                Drawable drawableLeft = getResources().getDrawable(
                        R.drawable.uncheckpic);
                drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(),
                        drawableLeft.getMinimumHeight());

                if (isExpanded) {
                    Drawable drawable = getResources().getDrawable(
                            R.drawable.upgray_arrow);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                            drawable.getMinimumHeight());
                    tv_cc.setCompoundDrawables(drawableLeft,null,drawable,null);
                } else {
                    Drawable drawable = getResources().getDrawable(
                            R.drawable.downgray_arrow);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                            drawable.getMinimumHeight());
                    tv_cc.setCompoundDrawables(drawableLeft,null,drawable,null);
                }


//                tv_cc.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        if (isExpanded) {
//                            Toast.makeText(ExpandListActivity.this,
//                                    "收缩",
//                                    Toast.LENGTH_SHORT).show();
//                        } else {
//                            Toast.makeText(ExpandListActivity.this,
//                                    "展开",
//                                    Toast.LENGTH_SHORT).show();
//                        }
//
//                    }
//                });
                ll.addView(v);

                return ll;
            }

            @Override
            public View getChildView(int groupPosition, int childPosition,
                                     boolean isLastChild, View convertView, ViewGroup parent) {
                LinearLayout ll = new LinearLayout(ExpandListActivity.this);
                ll.setOrientation(LinearLayout.HORIZONTAL);


                View v = LayoutInflater.from(ExpandListActivity.this).inflate(
                        R.layout.story_number_listitem4addhabit, ll, false);


                final AlbumItem ai = mArrayListAlbum.get(childPosition);
                final String album_name = ai.album_name;
                final String name = ai.title;
                final boolean isFav = ai.favorite;
                final String order = ai.sort + "";
                final String reslen = Tools.secToTime(ai.length);
                final String subtitle = "";

                TextView storynumber = (TextView) v
                        .findViewById(R.id.storynumber);
                TextView storytittle = (TextView) v
                        .findViewById(R.id.storytittle);
             //   TextView tv_seqno = (TextView) v.findViewById(R.id.tv_seqno);


                TextView tv_storylist = (TextView) v
                        .findViewById(R.id.tv_storylist);




                if (mArrayListAlbum != null) {
                    if (storynumber != null) {
//                        if ((childPosition + 1) < 10) {
//                            tv_seqno.setText("0" + (position + 1));
//                        } else {
//                            tv_seqno.setText("" + (position + 1));
//                        }

//                        if (highLightPosition == position) {
//                            holder.storynumber.setTextColor(Color.parseColor("#f6b559"));
//                            holder.img_playing_icon.setVisibility(View.VISIBLE);
//                            holder.frame_view.setVisibility(View.INVISIBLE);
//                        } else {
//                            holder.img_playing_icon.setVisibility(View.GONE);
//                            holder.frame_view.setVisibility(View.VISIBLE);
//                            holder.storynumber.setTextColor(mContext.getResources().getColor(
//                                    R.color.black_color));
//                        }



                        storynumber.setText(album_name + " 第" + order + "集" + " ("
                                + reslen + ")");

                        if (Tools.isEmpty(subtitle)) {
                            storytittle.setText(name);
                        } else {
                            storytittle.setText(subtitle);
                        }

//                        if (selectedPosition == position) {
//                            holder.moreLayout.setVisibility(View.VISIBLE);
//                        } else {
//                            holder.moreLayout.setVisibility(View.GONE);
//                        }
                    }
                }




//                TextView textView = getTextView();
//
//
//                textView.setText(getChild(groupPosition, childPosition).toString());
                ll.addView(v);
                return ll;
            }

            @Override
            public boolean isChildSelectable(int groupPosition, int childPosition) {
                return true;
            }

        };






         expandableListView = (ExpandableListView) findViewById(province);
        expandableListView.setAdapter(mAdapter);
        expandableListView.setGroupIndicator(null);
       // expandableListView.setDivider(getResources().getDrawable(R.drawable.backlines));
      //  lv.setChildDivider(getResources().getDrawable(R.drawable.diyline));

//        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
//            @Override
//            public void onGroupExpand(int groupPosition) {
//                int count = expandableListView.getExpandableListAdapter().getGroupCount();
//                for(int j = 0; j < count; j++){
//                    if(j != groupPosition){
//                        expandableListView.collapseGroup(j);
//                    }
//                }
//            }
//        });



//        expandableListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Toast.makeText(ExpandListActivity.this,
//                      "fffff",
//                        Toast.LENGTH_SHORT).show();
//            }
//        });


        expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
            @Override
            public void onGroupCollapse(int groupPosition) {

            }
        });

        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {

                int count = expandableListView.getExpandableListAdapter().getGroupCount();
                for(int j = 0; j < count; j++){
                    if(j != groupPosition){
                        expandableListView.collapseGroup(j);
                    }
                }

            }
        });

        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {

                boolean expanded = parent.isGroupExpanded(groupPosition);
                if (!expanded) {
                    getEpisode(mArrayList.get(groupPosition).id, groupPosition);
                    return true;
                }
                return false;


//                if (mArrayListAlbum.size() != 0 && mArrayListAlbum.get(groupPosition)!=null) {
//                    return false;
//                }


              //  return false;
            }
        });

        // 设置item点击的监听器
        expandableListView.setOnChildClickListener(new OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, final int childPosition, long id) {

                Toast.makeText(ExpandListActivity.this,
                        mAdapter.getChild(groupPosition, childPosition).toString(),
                        Toast.LENGTH_SHORT).show();

                Intent resultIntent = new Intent();
                resultIntent.putExtra("selectdata", mArrayListAlbum.get(childPosition));
                setResult(RESULT_OK, resultIntent);

                finish();

                return false;
            }
        });
    }
}